import { defineStore } from 'pinia'
import { getUnreadMessageList, updateAllMessageRead, unhandleAlert } from '@/api/message'
import { getAlertImageUrl, getUnhandledAlertMessage } from "@/api/alert"
import { alertPush, alertListPush } from '@/utils/alert'
import { useRoute } from 'vue-router'
import { getEquipmentIds } from '@/api/equipment'
import throttle from 'lodash/throttle';
interface IUnreadMessageItem {
    id: number
    alertMessageId: number
    alertGrade: string
    alertContent: string | null
    alertTime: string | Date
    equipmentId: string | number
}

interface IUseMessageStore {
    totalCount: number
    unreadMessageList: Array<IUnreadMessageItem>
}

export const useMessageStore = defineStore('messageStore', {
    state: () =>
    ({
        // 未读消息数量
        totalCount: 0,
        // 未读消息列表
        unreadMessageList: []
    } as IUseMessageStore),
    actions: {
        // 获取未读消息列表
        async getUnhandledAlertMessage() {
            const res = await getEquipmentIds('ALL')

            let params = { equipmentIds: res.data }
            const { data } = await unhandleAlert(<any>params)
            // const { data } = await getAlertImageUrl({ messageId: '', order: '', orderType: '', pageNum: 1, pageSize: 500 })
            this.totalCount = data.length || 0
            this.unreadMessageList = data || []
            // this.unreadMessageList.forEach((item: any) => {
            //     alertPush(item)
            // })
            // console.log(data);


        },

        // 更新全部消息已读
        updateAllMessageReadAction() {
            updateAllMessageRead().then(res => {
                this.totalCount = 0
                this.unreadMessageList = []
            })
        },

        // 添加未读消息列表
        addMessageAction(msg: any) {
            const index = this.unreadMessageList.findIndex(item => item.alertMessageId === msg.alertMessageId)


            if (index > -1) {
                this.unreadMessageList.splice(index, 1)


            } else {
                this.totalCount++
                throttle(() => {
                    alertPush(msg)
                }, 1000)
            }
            this.unreadMessageList.unshift(msg)


        },


        // 移除最新已读消息
        removeMessageAction(readId: number) {
            this.unreadMessageList.forEach((item, index) => {
                if (item.alertMessageId === readId) {
                    this.totalCount--
                    this.unreadMessageList.splice(index, 1)
                }
            })
        }
    }
})
